package com.nowcoder.community.controller;

import com.nowcoder.community.dao.DiscussPostMapper;
import com.nowcoder.community.dao.UserMapper;
import com.nowcoder.community.util.CommunityUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@Api(tags = "测试的controller")
@Controller
@RequestMapping("/alpha")
public class AlphaController {

    @ResponseBody
    @GetMapping("/test")
    public String test() {
        return "hello";
    }


    @GetMapping("/http")
    public void testHttp(HttpServletRequest request, HttpServletResponse response) {
        // 获取请求消息
        System.out.println(request.getMethod());
        System.out.println(request.getServletPath());

        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            String header = request.getHeader(name);
            System.out.println(name + "->" + header);
        }

        // 返回响应数据
        response.setContentType("text/html;charset=utf-8");
        // java 1.7 语法糖
        try (PrintWriter writer = response.getWriter()) {
            writer.write("<h1>hello</h1>");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 分页查询所有学生
    @RequestMapping(path = "/students", method = RequestMethod.GET)
    @ResponseBody
    public String getStudents(
            @RequestParam(value = "current", required = false, defaultValue = "1") Integer current,
            @RequestParam(value = "limit", required = false, defaultValue = "20") Integer limit) {
        System.out.println(current);
        System.out.println(limit);
        return "some student";
    }

    // 分页查询所有学生
    @RequestMapping(path = "/students/{id}", method = RequestMethod.GET)
    @ResponseBody
    public String getStudent(@RequestParam("id") Integer id) {
        System.out.println(id);
        return "one student";
    }

    /**
     * @RequestBody主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的)； GET方式无请求体，所以使用@RequestBody接收数据时，前端不能使用GET方式提交数据，
     * 而是用POST方式进行提交。
     */
    @PostMapping("/student")
    @ResponseBody
    public String addStudent(String name, String password) {
        System.out.println(name);
        System.out.println(password);
        return "one student";
    }

    @GetMapping("/teacher")
    @ResponseBody
    public ModelAndView getTeacher() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("name", "livmi");
        modelAndView.addObject("password", "123");
        modelAndView.setViewName("/demo/view");

        return modelAndView;
    }

    @GetMapping("/school")
    // dispatchServlet自动创建的Model对象，并持有引用
    public String getSchool(Model model) {
        model.addAttribute("name", "livmi");
        model.addAttribute("password", "123");
        return "/demo/view";
    }

    // 自动转json
    @ResponseBody
    @GetMapping("/emp")
    public Map<String, Object> getEmp() {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "zs");
        map.put("age", 45);
        map.put("edu", "nihao");
        return map;
    }

    // 自动转json
    @ResponseBody
    @GetMapping("/emps")
    public List<Map<String, Object>> getEmpList() {
        List<Map<String, Object>> list = new ArrayList<>();

        Map<String, Object> map = new HashMap<>();
        map.put("name", "zs");
        map.put("age", 45);
        map.put("edu", "nihao");
        list.add(map);

        map = new HashMap<>();
        map.put("name", "zsf");
        map.put("age", 450);
        map.put("edu", "nihaoya");
        list.add(map);
        return list;
    }

    // cookie的测试用例
    @ResponseBody
    @GetMapping("/cookie/set")
    public String setCookie(HttpServletResponse response) {
        // 创建cookie
        Cookie cookie = new Cookie("code", "520");
        // 设置有效路径
        cookie.setPath("/community/alpha");
        // 设置生存时间（秒）
        cookie.setMaxAge(60 * 10);
        response.addCookie(cookie);
        return "set cookies";
    }

    // cookie的测试用例
    @ResponseBody
    @GetMapping("/cookie/get")
    public String getCookie(@CookieValue("code") String code) {
        System.out.println(code);
        return "get cookies";
    }

    // session 示例
    @ResponseBody
    @GetMapping("/session/set")
    public String setSession(HttpSession session) {
        // session不用像cookie一样创建，声明springMVC会自动创建
        session.setAttribute("id",1);
        session.setAttribute("msg","text");
        return "set session";
    }

    // session 示例
    @ResponseBody
    @GetMapping("/session/get")
    public String getSession(HttpSession session) {
        // session不用像cookie一样创建，声明springMVC会自动创建
        System.out.println(session.getAttribute("id"));
        System.out.println(session.getAttribute("msg"));
        return "get session";
    }

    @ResponseBody
    @PostMapping("/ajax")
    public String testAjax(String name,int age){
        System.out.println(name+"\t"+age);
        return CommunityUtil.getJSONString(1,"ok");
    }

}
